package about_collections.xunhuanbianli;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 循环遍历
 * 常见的三种遍历
 *   for循环
 *  增强for循环(foreach)
 *  Iterator迭代器
 *
 */
public class XunHuanBianLi {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

        XunHuanBianLi xh =new XunHuanBianLi();
        xh.methodFor(list);
        System.out.println("===========================================");
        xh.methodForEach(list);
        System.out.println("===========================================");
        xh.methodIterator(list);
    }

        //for循环
    public void methodFor(ArrayList<String> list) {
        for (String message : list) {
            System.out.println("for循环遍历取出元素" + message);
        }
    }

        //foreach遍历
    public void methodForEach(ArrayList<String> list) {
//        list.forEach(s->System.out.println("foreach遍历取出元素"+s));
        System.out.println("=======");
        //parallelStream()转化为流进行操作,提高效率
        list.stream().forEach(s->System.out.println("stream().foreach遍历取出元素"+s));
        System.out.println("=======");
        //parallelStream()转化为流进行操作,并行操作,效率更高,但不保证顺序?,有并发问题
        list.parallelStream().forEach(s->System.out.println(".parallelStream().foreach并行stream遍历取出元素"+s));
    }

    //Iterator遍历器遍历
    public void methodIterator(ArrayList<String> list) {
        Iterator<String> it = list.iterator();
        System.out.println("Iterator删除前数据:" + list.toString());
        while (it.hasNext()) {
            String s = it.next();
            System.out.println("即将在遍历同时删除元素:" + s);
            it.remove();
        }
        System.out.println("Iterator删除后数据:" + list.toString());
    }


}
